﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text; 
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Context;

namespace NhibernateUtil
{
	public class NhibernateHelper
	{
		private static Configuration _configuration;
		static NhibernateHelper()
		{
			_configuration = new Configuration();

			_sessionFactory = _configuration
			//.Configure(GetFileFullName("Nhibernate.cfg.xml"))
            .Configure(Assembly.GetExecutingAssembly(), "NhibernateUtil.Nhibernate.cfg.xml")
			.BuildSessionFactory();
		}


		public static string GetFileFullName(string fileName)
		{
			return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + fileName;
			//return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + fileName;
            
		}
		private static ISessionFactory _sessionFactory;

		public static ISessionFactory SessionFactory
		{
			get { return _sessionFactory; }
		}

		public static Configuration Configuration
		{
			get { return _configuration; }
		}

		/// <summary>
		/// 获得当前Session
		/// </summary>
		/// <returns></returns>
		public static ISession GetCurrentSession()
		{
			return GetCurrentSession(false);
		}

		public static void BindCurrenSession(ISession session)
		{
			CurrentSessionContext.Bind(session);
		}

		public static void UnBindCurrenSession()
		{
			CurrentSessionContext.Unbind(SessionFactory);

		}

		public static void ExcuteUpdateSql(string sql)
		{
			ISession session = GetCurrentSession();
			session.CreateSQLQuery(sql).ExecuteUpdate();
		}

		/// <summary>
		/// 获得当前Session
		/// </summary>
		/// <param name="isThrowWhenNotFind">当没有发现当前Session时抛出异常</param>
		/// <returns></returns>
		public static ISession GetCurrentSession(bool isThrowWhenNotFind)
		{

			return SessionFactory.OpenSession();
			//if (CurrentSessionContext.HasBind(_sessionFactory))
			//    return _sessionFactory.GetCurrentSession();
			//if (isThrowWhenNotFind)
			//    throw new InvalidOperationException("没有在上下文中发现Session");
			//return null;
		}

		/// <summary>
		/// 获得数据库事务对象
		/// </summary>
		/// <param name="transaction"></param>
		/// <returns></returns>
		public static IDbTransaction GetTransaction(ITransaction transaction)
		{
			FieldInfo fieldInfo = transaction.GetType().GetField("trans",
										   BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.NonPublic);
			return (IDbTransaction)fieldInfo.GetValue(transaction);
		}
	}
}
